package com.killer.edu.oauth.oauth2.userdetail;

import com.killer.edu.oauth.entity.UserJwt;
import com.killer.edu.oauth.mult.MultAuthentication;
import com.killer.edu.oauth.mult.MultAuthenticationContext;
import com.killer.edu.oauth.mult.authenticator.MultAuthenticator;
import com.killer.edu.user.api.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class MultUserDetailsService implements UserDetailsService {

    @Autowired
    private List<MultAuthenticator> authenticators;

    /**
     * 根据用户名查找用户，若找到则封装成UserDetails信息并返回,UserJwt继承User继承UserDetails
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserJwt loadUserByUsername(String username) throws UsernameNotFoundException {
        MultAuthentication multAuthentication= MultAuthenticationContext.get();
        //判断是否是集成登录
        if (multAuthentication == null) {
            multAuthentication=new MultAuthentication();
        }
        multAuthentication.setUsername(username);
        UserDTO user = this.authenticate(multAuthentication);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //封装成UserDetails对象返回
        return new UserJwt(user.getName(),
                user.getPassword(),
                !user.getIsDel(),
                user.getAccountNonExpired(),
                user.getCredentialsNonExpired(),
                user.getAccountNonLocked(),
                this.obtainGrantedAuthorities(user),
                user.getId().toString());
    }

    private Collection<? extends GrantedAuthority> obtainGrantedAuthorities(UserDTO user) {
        //TODO 查询用户权限
        return new ArrayList<GrantedAuthority>();
    }

    private UserDTO authenticate(MultAuthentication multAuthentication) {
        if (multAuthentication != null) {
            //循环所有认证器
            for (MultAuthenticator authenticator : authenticators) {
                //找出支持这种认证类型的认证器
                if (authenticator.support(multAuthentication)) {
                    //使用支持这种认证类型的认证器进行认证
                    return authenticator.authenticate(multAuthentication);
                }
            }
        }
        return null;
    }
}
